package blackstar.plugin.monitor.reporter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import blackstar.agent.AgentConfig;
import blackstar.agent.event.EventDispatcherSupport;
import blackstar.agent.schedule.ScheduleEvent;
import blackstar.agent.schedule.ScheduleTask;

/**
 * @author RayWoo (ayufox@gmail.com)
 * 
 */
public class FileResultReporter extends EventDispatcherSupport implements
		ResultReporter
{
	private final static Log LOGGER = LogFactory
			.getLog(FileResultReporter.class);

	private Map<String, FileWriter> writers = new HashMap<String, FileWriter>();
	private String cronExpression = "0 0 0 * * ?";

	public FileResultReporter()
	{
		dispatch(new ScheduleEvent(cronExpression, new ScheduleTask()
		{
			public void schedule()
			{
				closeAll();
			}
		}));
	}

	public synchronized void closeAll()
	{
		for (FileWriter writer : writers.values())
		{
			try
			{
				writer.close();
			} catch (Exception e)
			{
				LOGGER.warn("Error When Close Writer", e);
			}
		}

		writers.clear();
	}

	public synchronized void report(ReportData data)
	{
		try
		{
			FileWriter writer = writers.get(data.getJvmid() + "_" + data.getId());
			if (writer == null)
			{
				String path = AgentConfig.getMonitorDataPath(data.getJvmid());
				String nowDate = new SimpleDateFormat("yyyyMMdd")
						.format(new Date());
				File dir = new File(path, nowDate);
				if (!dir.exists())
				{
					dir.mkdirs();
				}

				writer = new FileWriter(new File(dir, data.getId()), true);
				writers.put(data.getJvmid() + "_" + data.getId(), writer);
			}

			SimpleDateFormat logDateFormat = new SimpleDateFormat(
					"yyyyMMddHHmm");
			writer.write(logDateFormat.format(data.getTimestamp()) + "|"
					+ data.getData() + "\n");
			writer.flush();
		} catch (IOException e)
		{
			LOGGER.warn("Error log report", e);
		}
	}
}
